import Taro from '@tarojs/taro';
import interceptors from './interceptors';

interceptors.forEach((interceptorItem) => Taro.addInterceptor(interceptorItem));

type OptionType = {
    url: string;
    data?: object | string;
    method?: any;
    header: object;
    timeout: number;
};

export default {
    baseOptions(params, method = 'GET') {
        let { url, data } = params;
        // 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据，会将数据转换成 query string
        let contentType = 'application/json';
        contentType = params.contentType || contentType;

        const baseUrl = process.env.TARO_APP_API;

        const option: OptionType = {
            url: baseUrl + url,
            timeout: 10000,
            data: data,
            method: method,
            header: {
                'content-type': contentType,
            },
        };
        return Taro.request(option);
    },
    get(url: string, data?: object) {
        let option = { url, data };
        return this.baseOptions(option);
    },
    post(url: string, data?: object, contentType?: string) {
        let params = { url, data, contentType };
        return this.baseOptions(params, 'POST');
    },
    put(url: string, data?: object) {
        let option = { url, data };
        return this.baseOptions(option, 'PUT');
    },
    delete(url: string, data?: object) {
        let option = { url, data };
        return this.baseOptions(option, 'DELETE');
    },
};
